package me.leiusual.sharing.ui.account

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_account_agreement.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.ApiSharing

/**
 * Create by leiusual on 2018/7/19
 */
class AccountAgreementFragment : DaggerFragment() {

  private lateinit var webView: WebView

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_account_agreement, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    webView = WebView(context?.applicationContext)
    webView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
    layout_web_view.addView(webView)

    // 设置不用系统浏览器打开,直接显示在当前webView
    webView.webViewClient = object : WebViewClient() {

      override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        view?.loadUrl(url)
        return true
      }
    }

    webView.loadUrl("${ApiSharing.BASE_URL}/app/protocol")
  }

  override fun onResume() {
    super.onResume()

    webView.onResume()
  }

  override fun onPause() {
    super.onPause()

    webView.onPause()
  }

  override fun onDestroyView() {
    super.onDestroyView()

    webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
    webView.clearHistory()
    layout_web_view.removeView(webView)
    webView.destroy()
  }
}